<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['psy:consbasic:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['psy:consbasic:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['psy:consbasic:remove']">删除</el-button>
      </el-col>
      <right-toolbar @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange"  v-hasPermi="['psy:consbasic:list']">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="咨询师头像" align="center" prop="consAvatar">
        <template slot-scope="scope">
          <img :src="scope.row.consAvatar" alt="" style="width: 50px;height: 50px;">
        </template>
      </el-table-column>
      <el-table-column label="咨询师名称" align="center" prop="consName" :show-overflow-tooltip="true" />
      <el-table-column label="咨询师简介" align="center" prop="consBri" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="咨询时间" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleTime(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v>修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" @close="cancel" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="咨询师头像：" prop="consAvatar">
          <div class="uploaderText">
            <el-upload class="avatar-uploader" :action="uploadUrl" :headers="headers" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="text">
              <p>点击后选择咨询师照片上传</p>
              <p>格式：png、jpg</p>
              <p>大小：1M以内</p>
            </div>
          </div>


        </el-form-item>
        <el-form-item label="咨询师名称：" prop="teacherId">
          <el-select v-model.lazy="form.teacherId" placeholder="请选择" learable class="elSelect" style="width: 100%;">
            <el-option v-for="dict in getTeacherList" :key="dict.VALUE" :label="dict.TITLE"
              :value="dict.VALUE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="咨询师简介：" prop="consBri">
          <el-input v-model.trim="form.consBri" type="textarea" placeholder="请输入内容" maxlength="200" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="咨询师时间：" prop="remark">
          <div class="container" v-for="(item, index) in form.psyConsDateList" :key="index">
            <div class="left">
              <el-date-picker v-model="item.pcdDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <div class="right">
              <div v-for="(v, i) in item.psyConsTimeList" :key="i" style="margin-bottom: 5px;">
                <el-time-picker is-range v-model="v.value2" range-separator="至" start-placeholder="开始时间"
                  end-placeholder="结束时间" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="选择时间范围"
                  style="width: 60%;">
                </el-time-picker>
                <el-button type="text" @click="add(item, index)">添加时间段</el-button>
                <el-button type="text" @click="deleteTime(index, i)" :disabled="flag">删除</el-button>
              </div>

            </div>

          </div>
          <el-button type="text" @click="addItem" style="clear: both;">添加可预约时间</el-button>
          <el-button type="text" @click="delItem" style="clear: both;" :disabled="flagdel">删除</el-button>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="timeVisibke" width="30%" append-to-body>
      <el-tabs type="border-card" @tab-click="handleClick">
        <el-tab-pane v-for="(v, i) in timeTab" :label="v + '月'" :key="i">
          <div v-for="(item, index) in dataTime" style="display: flex;justify-content: space-between;">
            <p>{{ item.pcdDate }}<span style="margin-left: 5px;">{{ getWeek(item.pcdDate) }}</span></p>
            <div>
              <p v-for="(itens, index) in  item.psyConsTimeList">{{ itens.startTime.substring(11, 16)
              }}-{{ itens.endTime.substring(11, 16) }}</p>
            </div>
          </div>
        </el-tab-pane>
        <!-- <el-tab-pane label="配置管理">配置管理</el-tab-pane>
  <el-tab-pane label="角色管理">角色管理</el-tab-pane>
  <el-tab-pane label="定时任务补偿">定时任务补偿</el-tab-pane> -->
      </el-tabs>
    </el-dialog>
  </div>
</template>
  
<script>
import { getToken } from "@/utils/auth";
import { getSelector, consbasicList, consbasicAdd, updataConsbasic, getConsbasic, dateList, delConsbasic } from "@/api/psychological/basic"
export default {
  name: "Dict",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      names: [],
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      getTeacherList: [],
      timeVisibke: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      timeTab: [],
      timeTabList: [],
      dataTime: [],
      tiemTips: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      flag: true,
      flagdel: true,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      // 表单参数
      form: {
        psyConsDateList: [
          {
            pcdDate: '',
            psyConsTimeList: [{ value2: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)], }]
          }],
        consAvatar: '',
        teacherId: ''
      },
      imageUrl: '',
      // 表单校验
      rules: {

        consAvatar: [
          { required: true, message: "请上传咨询师照片" }
        ],
        teacherId: [
          { required: true, message: "请选择咨询师", trigger: "change" }
        ],
        consBri: [
          { required: true, message: "请填写咨询师简介", trigger: "blur" }
        ],
      }
    };
  },
  computed: {
    userInfor() {
      return this.$store.state.user;
    }
  },
  created() {
    console.log(this.userInfor,'skksk')
    if(this.userInfor.permissions.includes('psy:consbasic:list')) {
      getSelector().then(res => {
      this.getTeacherList = res.data
         this.getList();
    })
 
        }
    
  },
  methods: {
    /** 查询字典类型列表 */
    getList() {
      consbasicList(this.queryParams).then(response => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    // 添加可预约时间
    addItem() {
      this.form.psyConsDateList.push({
        pcdDate: '',
        psyConsTimeList: [{ value2: [new Date(), new Date()] }]
      })
      this.flagsdel()
    },
    // 判断数组长度
    flags() {
      this.form.psyConsDateList.forEach((item) => {
        if (item.psyConsTimeList.length < 2) {
          this.flag = true
        } else {
          //先赋值为true再赋为false, 不然会没反应
          this.flag = true
          this.flag = false
        }
      })
    },
    getWeek(dateStr) {
      let date = '' //周几
      let weeks = {
        "0": '星期日',
        "1": '星期一',
        "2": '星期二',
        "3": '星期三',
        "4": '星期四',
        "5": '星期五',
        "6": '星期六',
      }
      date = new Date(dateStr)
      let weekIndex = date.getDay();
      date = weeks[weekIndex];
      return date
    },
    // 查看时间详情
    handleTime(row) {
      this.timeTab = []
      this.dataTime = []
      this.timeTabList = []
      dateList(row.pcbId).then(res => {
        this.timeVisibke = true
        res.data.forEach(e => {
          this.timeTab.push(e.pcdDate.substring(5, 7))
          if (e.pcdDate.substring(5, 7) == e.pcdDate.substring(5, 7)) {
            this.timeTabList.push(e)
          }
        })

        this.timeTab = Array.from(new Set(this.timeTab))
        console.log(this.timeTab, this.timeTabList, 'fdsjfhjk')
        this.timeVisibke = true
        this.title = '咨询时间'
        this.timeTabList.forEach(e => {
          if (this.timeTab[0] == e.pcdDate.substring(5, 7)) {
            this.dataTime.push(e)
          }
        })
      })
    },
    handleClick(tab, event) {
      this.dataTime = []

      this.timeTabList.forEach(e => {
        if (tab.label.substring(0, 2) == e.pcdDate.substring(5, 7)) {
          this.dataTime.push(e)
        }
      })
    },
    // 判断数组长度
    flagsdel() {
      if (this.form.psyConsDateList.length < 2) {
        this.flagdel = true
      } else {
        //先赋值为true再赋为false, 不然会没反应
        this.flagdel = true
        this.flagdel = false
      }
    },
    // 添加时间段
    add(item, index) {
      this.form.psyConsDateList[index].psyConsTimeList.push({ value2: [new Date(), new Date()] })
      if (this.form.psyConsDateList[index].psyConsTimeList.length == 1) {
        this.flags = true
      } else {
        this.flag = true
        this.flag = false
      }
      // this.flags()
    },
    deleteTime(item, index) {
      console.log(item, index, this.form.psyConsDateList, 'dfj')
      // this.form.psyConsDateList
      this.form.psyConsDateList[item].psyConsTimeList.splice(index, 1)
      this.flags()
    },
    delItem() {
      this.form.psyConsDateList.length = this.form.psyConsDateList.length - 1

      this.flagsdel()
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.consAvatar = res.url

    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'png' || 'jpg';
      const isLt2M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!');
      }
      return isJPG && isLt2M;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.imageUrl = ''
      this.form = {
        psyConsDateList: [
          {
            pcdDate: '',
            psyConsTimeList: [{ value2: [new Date(2016, 24, 10, 23, 0), new Date(2016, 9, 10, 0, 0)] }]
          }],
        consAvatar: '',
        teacherId: ''
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "新增咨询师";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pcbId)
      this.names = selection.map(item => item.consName)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = true
      getConsbasic(row.pcbId).then(res => {
        console.log(res, '获取详情')
        this.form = res.data
        this.imageUrl = res.data.consAvatar
        
        if(this.form.psyConsDateList) {
          this.form.psyConsDateList.forEach(item => {
          item.psyConsTimeList.forEach(e => {
            e.value2 = []
            e.endTime = e.endTime.substring(11)
            e.startTime = e.startTime.substring(11)
            e.value2.push(e.startTime, e.endTime)
          })
        })
        }
        
        // this.imageUrl = res.data.consAvatar
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.tiemTips = false
      console.log(this.form, 'fdsh2')
      if(this.form.psyConsDateList[0].pcdDate) {
        for (var i = 0; i < this.form.psyConsDateList.length; i++) {
        for (var j = i + 1; j < this.form.psyConsDateList.length; j++) {
          if (this.form.psyConsDateList[i].pcdDate == this.form.psyConsDateList[j].pcdDate) {
            this.tiemTips = true
          }
        }
      }
      this.form.psyConsDateList.forEach(item => {


        item.psyConsTimeList = item.psyConsTimeList.map(e => {
          return {
            startTime: item.pcdDate + ' ' + e.value2[0],
            endTime: item.pcdDate + ' ' + e.value2[1],
          }
        })
        console.log(item.psyConsTimeList.length, 'dfddfcsfdfd')
        for (var i = 0; i < item.psyConsTimeList.length; i++) {
          for (var j = i + 1; j < item.psyConsTimeList.length; j++) {
            if (item.psyConsTimeList[i].startTime == item.psyConsTimeList[j].startTime && item.psyConsTimeList[i].endTime == item.psyConsTimeList[j].endTime) {
              this.tiemTips = true
            }
          }
        }
      })
      }

     
      console.log(this.tiemTips, 'tiemTipstiemTipstiemTips')
      if (this.tiemTips === false) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.pcbId != undefined) {
              this.form.classNumber = Number(this.form.classNumber)
              updataConsbasic(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.form = {};
                this.getList();
              });
            } else {
              consbasicAdd(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.form = {};
              });
            }
          }
        });
      } else {
        this.$modal.msgError("添加时间日期不能相同");
      }


    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.pcbId || this.ids;
      this.names = row.consName || this.names;
      this.$modal
        .confirm('是否确认删除咨询师"' + this.names + '"的数据项？')
        .then(function () {
          return delConsbasic(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });

    },
  }
};
</script>
<style scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
  border: 1px dashed red;
}

.uploaderText {
  display: flex;
}

.text {
  margin-left: 15px;
  line-height: 35px;
  color: #9A9A9A;
}

.container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.left {
  width: 30%
}

.right {
  width: 65%
}
</style>